package home.contaduria.domain;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Component;

@Component
public class IncomeDataOnDemand {

    private Random rnd = new java.security.SecureRandom();

    @PersistenceContext
    private EntityManager entityManager;
    private List<Income> data;
    private Client client;
    private IncomeType incomeType;

    public Income getNewTransientIncome(int index) {
        home.contaduria.domain.Income obj = new home.contaduria.domain.Income();
        obj.setOperationDate(new Date());
        obj.setOperationSum(BigDecimal.valueOf(index));
        obj.setClient(client);
        obj.setType(incomeType);
        return obj;
    }

    public Income getSpecificIncome(int index) {
        if (data == null) {
            throw new IllegalStateException("Method init was not invoked");
        }
        if (index < 0)
            index = 0;
        if (index > (data.size() - 1))
            index = data.size() - 1;
        Income obj = data.get(index);
        return entityManager.find(Income.class, obj.getId());
    }

    public Income getRandomIncome() {
        if (data == null) {
            throw new IllegalStateException("Method init was not invoked");
        }
        Income obj = data.get(rnd.nextInt(data.size()));
        return entityManager.find(Income.class, obj.getId());
    }

    public void init(Client client, IncomeType incomeType) {
        this.client = client;
        this.incomeType = incomeType;
        data = findIncomeEntities(0, 10);
        if (data == null)
            throw new IllegalStateException("Find entries implementation for 'Income' illegally returned null");
        if (!data.isEmpty()) {
            return;
        }

        data = new java.util.ArrayList<home.contaduria.domain.Income>();
        for (int i = 0; i < 10; i++) {
            home.contaduria.domain.Income obj = getNewTransientIncome(i);
            entityManager.persist(obj);
            entityManager.flush();
            data.add(obj);
        }
    }

    public List<Income> findIncomeEntities(int firstResult, int maxResults) {
        return entityManager.createQuery("SELECT i FROM Income i", Income.class).setFirstResult(firstResult).setMaxResults(maxResults)
                .getResultList();
    }
}
